"ui";

const storageUtils = require ("./storageUtils.js");
const clockInHandles = require('./clockInHandle.js');
const comdUtils = require("./commondUtils.js");

// 校验无障碍服务
openAutoService();

// 设置日志文件
storageUtils.setLogDir(false);

ui.layout(
    <vertical>
        <horizontal padding="16" id="localBtnArea">
            <Switch id="signIntervalOpenFlag"
                text="本地定时任务"
                checked="false"
                textSize="15sp"
                textColor="black"
                layout_gravity="center"
            />
            <button id="testBtn" text="测试本地定时任务" layout_gravity="center" style="Widget.AppCompat.Button.Colored" w="auto"/>
        </horizontal>
        <horizontal padding="16" id="serverBtnArea">
            <Switch id="wsConnectFlag"
                text="服务端连接"
                checked="false"
                textSize="15sp"
                textColor="black"
                layout_gravity="center"
            />
        </horizontal>
        <horizontal padding="16">
            <button id="signBtn" text="立即签到" layout_gravity="center" style="Widget.AppCompat.Button.Colored" w="auto"/>
            <button id="consoleBtn" text="控制台" layout_gravity="center" style="Widget.AppCompat.Button.Colored" w="auto"/>
            <button id="logBtn" text="日志" layout_gravity="center" style="Widget.AppCompat.Button.Colored" w="auto"/>
        </horizontal>
    </vertical>
);

ui.wsConnectFlag.on("click", (data) => {
    if (!data.checked) {
        clockInHandles.closeServer();
        return;
    }
    const startConnectTime = Date.now();
    clockInHandles.connectServer();
    threads.start(function () {
        // 等待连接完成
        while (true) {
            sleep(100);
            if (clockInHandles.isConnectServer()) {
                ui.run(() => { ui.wsConnectFlag.checked = true; });
                break;
            }
            // 最晚等待5S
            if (((Date.now() - startConnectTime) > 5000)) {
                ui.run(() => { ui.wsConnectFlag.checked = false; });
                toast("连接服务端超时！5s");
                break;
            }
        }
    });
});

ui.signIntervalOpenFlag.on("click", (data) => {
    if (!data.checked) {
        threads.start(function () {
            clockInHandles.stopClockInTask();
            toast("定时任务已停止");
        });
        return;
    }
    threads.start(function () {
        clockInHandles.runClockInTask();
        toast("启动定时任务成功");
    });
});

ui.testBtn.on("click", () => {
    threads.start(function () {
        clockInHandles.testClockInTask();
    });
});

ui.signBtn.on("click", () => {
    threads.start(function () {
        clockInHandles.execSingIn();
    });
});

ui.consoleBtn.on("click", () => {
    threads.start(function () {
        console.hide();
        sleep(500);
        console.show();
        console.setTitle("控制台");
    });
});

ui.logBtn.on("click", () => {
    app.viewFile(files.join(storageUtils.ROOT_DIR_NAME, storageUtils.LOG_FILENAME));
});

// 当用户回到本界面时，resume事件会被触发
ui.emitter.on("resume", function() {
    ui.wsConnectFlag.checked = clockInHandles.isConnectServer();
    ui.signIntervalOpenFlag.checked = clockInHandles.isOpenInterval();
});

const setting = clockInHandles.getSettingData();
if (!setting.intervalModel.includes('websocket') || comdUtils.isBlank(setting.websocketUrl)) {
    ui.serverBtnArea.setVisibility(android.view.View.GONE);
} 
if (!setting.intervalModel.includes('local')) {
    ui.localBtnArea.setVisibility(android.view.View.GONE);
}

/**
 * 检查无障碍服务，提示开启
 */
function openAutoService() {
    if (auto.service != null) {
        return;
    }
    ui.run(() => {
        confirm("无障碍服务未开启！是否跳转至无障碍界面？").then(result => {
            if (result) {
                app.startActivity({action: "android.settings.ACCESSIBILITY_SETTINGS"});
            }
        });
    });
}

// 播放音乐保活脚本
function startKeepAlive() {
    let filepath = './res/npSound.mp3';
    if (!files.exists(filepath)) {
        filepath = files.join(files.getSdcardPath(), 'm3-clock/npSound.mp3');
        if (!files.exists(filepath)) {
            console.error("保活音乐不存在：", filepath);
			alert("保活音乐不存在！" + filepath);
            return;
        }
    }
    media.playMusic(filepath, 1, true);
}
startKeepAlive();